package com.alu4r.atcrowdfunding.interceptor;

import com.alu4r.atcrowdfunding.bean.Member;
import com.alu4r.atcrowdfunding.bean.User;
import com.alu4r.atcrowdfunding.util.Constant;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入到LoginInterceptor");
        Set<String> set = new HashSet<>();
        //定义哪些路径不需要拦截
        set.add("/index.htm");
        set.add("/register.htm");
        set.add("/register.do");
        set.add("/login.htm");
        set.add("/login.do");
        set.add("/doLogin.do");
        set.add("/logout.do");
        set.add("/autoLogin.do");

        //获取请求路径
        String servletPath = request.getServletPath();
        System.out.println("当前请求路径："+servletPath);
        if(set.contains(servletPath)){
            return true;
        }
        //判断用户是否登录，如果登录就放行
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.LOGIN_USER);
        Member member = (Member) session.getAttribute(Constant.LOGIN_MEMBER);
        if(user != null || member != null){
            return true;
        }else {
            response.sendRedirect(request.getContextPath()+"/login.htm");
            return false;
        }
    }
}
